package com.feib.ebilling.job;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.feib.ebilling.job.service.FeeLiquidationFileService;
import com.feib.ebilling.job.service.FtpService;
import com.feib.ebilling.job.util.StringUtils;

/**
 * @title (#)FeeLiquidationFile.java<br>
 * @description 中租車貸策略聯盟手續費清算明細檔格式<br>
 * @author Fiona Huang<br>
 * @version 1.0.0 2011/11/10
 * @version 1.0.1 2012/10/17
 * @copyright Far Eastern International Bank Copyright (c) 2011<br>
 * @2011/11/10 create by Fiona Huang<br>
 * @2012/10/17 modified by Monica Tan For 中租迪和拆分為中租+合迪(N-201210248)<br>
 */


@Service("feeLiquidationFile")
public class FeeLiquidationFile {
	
	/* 中租車貸策略聯絡的代號  */
	public static final String CHAILEASE = "865170966930";
	
	/* 合迪車貸策略聯絡的代號 */
	private static final String FINATRADE = "865170966990";

	/* 輸入參數的業者代號 */
	private static String groupNo;

	/* 輸入參數的業者名稱 */
	private static String groupName;

	/* 最終產出檔名 */
	private static String resultFileName;
	
	public static Logger logger = LoggerFactory.getLogger(FeeLiquidationFile.class);

	public static final SimpleDateFormat BASIC_DATE_TIME_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	@Resource(name="feeLiquidationFileService")
    private FeeLiquidationFileService feeLiquidationFileService;
	@Resource(name = "ftpService")
	private FtpService ftpService;

	public static void main(String[] args) {

		/* 傳輸日期  --> 銷帳日期當日 */
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		Date dNow = new Date();
		String processDate = dateFormat.format(dNow);
		if (null == args || 0 == args.length) {
			System.out.println("FeeLiquidationFile [" + groupNo + "][" + dateFormat.format(dNow) + "]");
			logger.info("FeeLiquidationFile： [沒有傳入業者代號]");
			return;
		}else if (1 == args.length){	
			/* 處理系統日當日所有中租回饋檔案 */
			groupNo = args[0];
		}else if (2 == args.length){
			/* 指定日期參數 */
			groupNo = args[0];
			processDate = args[1];
		}
		
		if (groupNo.equals(CHAILEASE)) {
			groupName = "中租";
			resultFileName = "TSBRFEE_feib-carloan_";
		} else if (groupNo.equals(FINATRADE)) {
			groupName = "合迪";
			resultFileName = "FINTSBRFEE_feib-carloan_";
		} else {
			System.out.println("WrittenOffFeedback [不知名的業者代號-執行結束]");
			logger.info("WrittenOffFeedback [不知名的業者代號-執行結束]");
			return; // 結束main()
		}
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				new String[] { "applicationContext-config.xml",	"applicationContext-dao.xml",
						       "applicationContext-properties.xml" });

		Date start = new Date();
		logger.info("[開始] {}車貸策略聯盟手續費清算明細檔  - {}", groupName, BASIC_DATE_TIME_FORMAT.format(start));
		try {
			FeeLiquidationFile feeLiquidationFile = (FeeLiquidationFile) ctx.getBean("feeLiquidationFile");
			/* 依日期產生檔案 */
			logger.info("銷帳日期：" + processDate);
			if (feeLiquidationFile.doFeedBack(processDate)) {
				logger.info("檔案產生成功：" + processDate);
			} else {
				logger.info("檔案產生失敗：" + processDate);
			}
		} catch (Exception e) {
			logger.error("[錯誤]" + e.getMessage(), e);
		} finally {
			Date end = new Date();
			logger.info("[結束] {}車貸策略聯盟手續費清算明細檔 - {}",groupName , BASIC_DATE_TIME_FORMAT.format(start));
			logger.info("共費時 - " + ((end.getTime() - start.getTime()) / 1000) + " 秒");
		}
	}
	
	public boolean doFeedBack(String processDate) {
		try {
			boolean bRtn = true;
			logger.info("{}車貸策略聯盟帳單業者代碼: {}", groupName, groupNo);
			/* 產生銷帳明細 */
			String sbf =  this.feeLiquidationFileService.writeoffByFile(processDate, groupNo,groupName);
			/* 轉上傳至業者端FTP Sever */
			String sFileName = resultFileName + processDate + ".TXT";
			ftpService.putFTPFile(groupNo, processDate, sbf, sFileName);
			
			/* 每月1號產生上個月月檔 */
			if (processDate.substring(processDate.length() - 2 ,processDate.length()).equals("01")) {				
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
				Date date = dateFormat.parse(processDate); 
				GregorianCalendar gc = new GregorianCalendar();
				gc.setTime(date);
				gc.add(Calendar.DATE, -1);                
				String lastMonth = String.valueOf(gc.get(Calendar.YEAR)) + StringUtils.PadString("R", "0", 2, String.valueOf(gc.get(Calendar.MONTH) + 1));
				logger.info("銷帳月份：" + lastMonth);
				/* 產生銷帳明細 */
				sbf =  this.feeLiquidationFileService.writeoffByFile(lastMonth, groupNo,groupName);
				/* 轉上傳至業者端FTP Sever */
				sFileName = resultFileName + lastMonth + ".TXT";
				ftpService.putFTPFile(groupNo, lastMonth, sbf, sFileName);
			}			
			return bRtn;
		} catch (Exception ex) {
			logger.error("[錯誤]" + ex.toString(), ex);
			return false;
		}
	}
}
